//
//  EFReturnGoodsViewController.m
//  EnjogFood
//
//  Created by guocheng on 2017/6/10.
//  Copyright © 2017年 wf. All rights reserved.
//

#import "EFReturnGoodsViewController.h"
#import "EFReturnGoodsTypeView.h"
#import "EFReturnGoodsTypeCell.h"
#import "EFReturnGoods.h"
#import "EFChooseReturnGoodsViewController.h"
#import "EFReturnGoodsViewItem.h"
#import "EFReturnGoodsViewCell.h"
#import "EFReturnGoods.h"
#import "EFConfirmView.h"
#import "EDJObjectData.h"
#import "EFReturnDetailViewController.h"
#import "iToast.h"

@interface EFReturnGoodsViewController()<UITableViewDelegate, UITableViewDataSource>

@property(strong,nonatomic)UITableView* tableView;
@property(nonatomic, strong)NSMutableArray *dataArray;

@property(strong,nonatomic) UIButton *okBtn;
@property(strong,nonatomic)EFConfirmView* confirmView;
@property (strong, nonatomic) UIView *rightBtnView;
@property (strong, nonatomic) UIButton *deleteBtn;

@property(strong,nonatomic)NSString* orderNo;
@property(strong,nonatomic)NSString* receiver;
@property(strong,nonatomic)NSString* phone;
@property(strong,nonatomic)EFRetrunReasonItem* reason;
@property(strong,nonatomic)NSString* desc;
@property(strong,nonatomic)NSString* returnId;



@end

@implementation EFReturnGoodsViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self initData];
    
    
    //右按钮
    [self.rightBtnView addSubview:self.deleteBtn];
    self.deleteBtn.left = self.rightBtnView.width - 20 - self.deleteBtn.width;
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBtnView];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chooseGoods:) name:IC_CHOOSE_GOODS_NOTIFICATION object:nil];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        self.title = @"选择退换货商品";
        self.dataArray = [NSMutableArray array];
    }
    return self;
}

-(instancetype)initWithOrderNo:(NSString *)orderNo receiver:(NSString *)receiver phone:(NSString *)phone reason:(EFRetrunReasonItem *)reason desc:(NSString *)desc{
    self = [self init];
    if(self){
        self.orderNo = orderNo;
        self.receiver = receiver;
        self.phone = phone;
        self.reason = reason;
        self.desc = desc;
    }
    return self;
}

-(void)initView{
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.okBtn];
    
}

-(void)chooseGoods:(NSNotification*)notifycation{
    EFReturnGoods* returnGoods = (EFReturnGoods*)notifycation.object;
    if(returnGoods != nil){
        NSInteger returnStartIndex = 0 ;
        NSInteger replaceStartIndex = 0 ;
        for(int i = 0;i< self.dataArray.count; ++i){
            if([[self.dataArray objectAtIndex:i] isKindOfClass:[EFReturnGoodsTypeView class]]){
                EFReturnGoodsTypeView* typeItem = (EFReturnGoodsTypeView*)[self.dataArray objectAtIndex:i];
                if(typeItem.type == 0){
                    returnStartIndex = i;
                }else if(typeItem.type == 1){
                    replaceStartIndex = i;
                }
            }
        }
        if(returnGoods.type == 0){  //退货
            NSMutableIndexSet* indexSet = [NSMutableIndexSet indexSet];
            for(int k = 0; k < returnGoods.selectArray.count; ++k){
                EFReturnGoodsViewItem* selectItem = [returnGoods.selectArray objectAtIndex:k];
                Boolean bHit = false;
                for(int j = returnStartIndex + 1;j< self.dataArray.count; ++j){
                    if([[self.dataArray objectAtIndex:j] isKindOfClass:[EFReturnGoodsViewItem class]]){
                        EFReturnGoodsViewItem* returnItem = (EFReturnGoodsViewItem*)[self.dataArray objectAtIndex:j];
                        
                        if([returnItem.id isEqualToString:selectItem.id]){
                            returnItem.qty += selectItem.qty;
                            [indexSet addIndex:k];
                        }
                    }
                }
            }
            [returnGoods.selectArray removeObjectsAtIndexes:indexSet];
            int start = replaceStartIndex;
            for(NSObject* object in returnGoods.selectArray){
                EFReturnGoodsViewItem* insertItem = (EFReturnGoodsViewItem*)object;
                insertItem.hideSelect = true;
                insertItem.type = 0;
                [self.dataArray insertObject:insertItem atIndex:start++];
            }
            [self.tableView reloadData];
        }else if(returnGoods.type == 1){
            NSMutableIndexSet* indexSet = [NSMutableIndexSet indexSet];
            for(int k = 0; k < returnGoods.selectArray.count; ++k){
                EFReturnGoodsViewItem* selectItem = [returnGoods.selectArray objectAtIndex:k];
                Boolean bHit = false;
                for(int j = replaceStartIndex + 1;j< self.dataArray.count; ++j){
                    if([[self.dataArray objectAtIndex:j] isKindOfClass:[EFReturnGoodsViewItem class]]){
                        EFReturnGoodsViewItem* returnItem = (EFReturnGoodsViewItem*)[self.dataArray objectAtIndex:j];
                        
                        if([returnItem.id isEqualToString:selectItem.id]){
                            returnItem.qty += selectItem.qty;
                            [indexSet addIndex:k];
                        }
                    }
                }
            }
            [returnGoods.selectArray removeObjectsAtIndexes:indexSet];
            int start = self.dataArray.count;
            for(NSObject* object in returnGoods.selectArray){
                EFReturnGoodsViewItem* insertItem = (EFReturnGoodsViewItem*)object;
                insertItem.hideSelect = true;
                insertItem.type = 1;
                [self.dataArray insertObject:insertItem atIndex:start++];
            }
            [self.tableView reloadData];
        }
    }
    [self setOkBtnText];
}

-(void)initData{
    [self.dataArray removeAllObjects];
    EFReturnGoodsTypeView* item = [[EFReturnGoodsTypeView alloc] init];
    item.title = @"退货商品";
    item.type = 0;
    [self.dataArray addObject:item];
    
    
    EFReturnGoodsTypeView* item2 = [[EFReturnGoodsTypeView alloc] init];
    item2.title =  @"换货商品";
    item2.type = 1;
    
    [self.dataArray addObject:item2];
    [self.tableView reloadData];
    
}

-(void)onClickOk{
    NSMutableArray *selectArray = [NSMutableArray arrayWithCapacity:10];
    for (NSInteger i = 0; i < self.dataArray.count; i++) {
        NSObject *object =  [self.dataArray objectAtIndex:i];
        if([object isKindOfClass:[EFReturnGoodsViewItem class]]){
            EFReturnGoodsViewItem* itemOne = (EFReturnGoodsViewItem*)object;
            Boolean bCounted = false;
            for (NSInteger j = 0; j < selectArray.count; j ++) {
                EFReturnGoodsViewItem *uItem = [selectArray objectAtIndex:j];
                if ([itemOne.id isEqualToString:uItem.id]) {
                    bCounted = true;
                }
            }
            if(bCounted)
                continue;
            
            for (NSInteger j = i + 1; j < self.dataArray.count; j++){
                NSObject *object =  [self.dataArray objectAtIndex:j];
                if([object isKindOfClass:[EFReturnGoodsViewItem class]]){
                    EFReturnGoodsViewItem* itemTwo = (EFReturnGoodsViewItem*)object;
                    if ([itemOne.id isEqualToString:itemTwo.id]) {
                        itemOne.qty =  itemOne.qty + itemTwo.qty;
                    }
                }
            }
            [selectArray addObject:itemOne];
        }
    }
    if(selectArray.count == 0){
        [self selectReturnGoods:0];
    }else{
        NSMutableArray *returnArray = [NSMutableArray arrayWithCapacity:10];
        NSMutableArray *replaceArray = [NSMutableArray arrayWithCapacity:10];
        for (NSInteger i = 0; i < self.dataArray.count; i++) {
            NSObject *object =  [self.dataArray objectAtIndex:i];
            if([object isKindOfClass:[EFReturnGoodsViewItem class]]){
                EFReturnGoodsViewItem* returnItem = (EFReturnGoodsViewItem*)object;
                NSDictionary *dic = [NSDictionary dictionary];
                dic = @{
                        @"order_product_id":returnItem.id,
                        @"qty": [NSString stringWithFormat:@"%ld",returnItem.qty]
                        };
                if(returnItem.type == 0){
                    [returnArray addObject:dic];
                }else if(returnItem.type == 1){
                    [replaceArray addObject:dic];
                }
            }
        }
        
        NSDictionary *dic = [NSDictionary dictionary];
        dic = @{
                @"return":returnArray,
                @"exchange":replaceArray,
                @"token":APP_CONTEXT.accountManager.accountInfo.token,
                @"name":self.receiver,
                @"phone":self.phone,
                @"reason_id":self.reason.id,
                @"reason":self.desc,
                @"orderId":self.orderId
                };
        NSString *retrunBody = [EDJObjectData jsonStringWithObject:dic];
        [APP_CONTEXT.net requestReturn:retrunBody OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
            if(code == 0){
                if([info objectForKey:@"returnId"]){
                    self.returnId = [info objectForKey:@"returnId"];
                }
                [[UIApplication sharedApplication].keyWindow addSubview:self.confirmView];
            }else{
                [[iToast makeText:message]show];
            }
        }];
        
    }
}

-(void)onClickRemove{
    __weak typeof(self) weakSelf = self;
    RIButtonItem *cancel = [RIButtonItem itemWithLabel:@"取消" action:^{
        //[weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    RIButtonItem *ok = [RIButtonItem itemWithLabel:@"确认" action:^{
        [weakSelf initData];
    }];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"确认清空商品？" message:nil cancelButtonItem:cancel otherButtonItems:ok,nil];
    [alertView show];

    [self setOkBtnText];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICTableViewItem *item = self.dataArray[indexPath.row];
    return item.viewHeight;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dataArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICTableViewItem* item = self.dataArray[indexPath.row];
    NSString *identifier = NSStringFromClass(item.viewClass);
    ICTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell = [[item.viewClass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if ([item isKindOfClass:[ICTableViewItem class]]) {
        [cell setObject:item];
    }
    
    if ([item isKindOfClass:[EFReturnGoodsTypeView class]]) {
        ((EFReturnGoodsTypeCell*)cell).addblock = ^(NSInteger type){
            [self selectReturnGoods:type];
        };
    }
    if ([item isKindOfClass:[EFReturnGoodsViewItem class]]) {
        EFReturnGoodsViewItem* goodItem = (EFReturnGoodsViewItem*)item;
        ((EFReturnGoodsViewCell *)cell).changeblock2 = ^(NSInteger count,Boolean bAdd){
            if(bAdd){
                int curCount = [self getItemTotalCount:goodItem.id];
                if(curCount < goodItem.totalCount){
                    count++;
                    goodItem.qty = count;
                    [self.tableView reloadData];
                }else{
                    [[iToast makeText:@"亲，不能再增加啦~"]show];
                }
            }else{
                goodItem.qty = count;
                [self.tableView reloadData];
            }
            
        };
    }
    
    return cell;
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    ICTableViewItem* item = self.dataArray[indexPath.row];
    if([item isKindOfClass:[EFReturnGoodsViewItem class]]){
        return YES;
    }else{
        return NO;
    }
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == self.tableView){
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            [self.dataArray removeObjectAtIndex:indexPath.row];
            [self.tableView reloadData];
            [self setOkBtnText];
        }
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}



- (UIView *)rightBtnView{
    if (!_rightBtnView) {
        _rightBtnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 22)];
        _rightBtnView.backgroundColor = [UIColor whiteColor];
    }
    return _rightBtnView;
}

- (UIButton *)deleteBtn{
    if (!_deleteBtn) {
        _deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
        [_deleteBtn setImage:IMG(@"address__edit_icon") forState:UIControlStateNormal];
        [_deleteBtn setImage:IMG(@"address__edit_icon") forState:UIControlStateSelected];
        [_deleteBtn addTarget:self action:@selector(onClickRemove) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteBtn;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kStatusBarHeight  -  50 )];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
    }
    return _tableView;
}


-(UIButton *)okBtn{
    if(_okBtn == NULL){
        _okBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        _okBtn.top = kScreenHeight - kStatusBarHeight -  50;
        _okBtn.backgroundColor = RGBCOLOR(0x69BA45);
        _okBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        _okBtn.titleLabel.textColor = [UIColor whiteColor];
        [_okBtn setTitle:@"下一步" forState:UIControlStateNormal];
        [_okBtn addTarget:self action:@selector(onClickOk) forControlEvents:UIControlEventTouchUpInside];
    }
    return _okBtn;
}

-(void)selectReturnGoods:(NSInteger)type{
    NSMutableArray *selectArray = [NSMutableArray arrayWithCapacity:10];
    for (NSInteger i = 0; i < self.dataArray.count; i++) {
        NSObject *object =  [self.dataArray objectAtIndex:i];
        if([object isKindOfClass:[EFReturnGoodsViewItem class]]){
            EFReturnGoodsViewItem* itemOne = (EFReturnGoodsViewItem*)object;
            Boolean bCounted = false;
            for (NSInteger j = 0; j < selectArray.count; j ++) {
                EFReturnGoodsViewItem *uItem = [selectArray objectAtIndex:j];
                if ([itemOne.id isEqualToString:uItem.id]) {
                    bCounted = true;
                }
            }
            if(bCounted)
                continue;
            
            for (NSInteger j = i + 1; j < self.dataArray.count; j++){
                NSObject *object =  [self.dataArray objectAtIndex:j];
                if([object isKindOfClass:[EFReturnGoodsViewItem class]]){
                    EFReturnGoodsViewItem* itemTwo = (EFReturnGoodsViewItem*)object;
                    if ([itemOne.id isEqualToString:itemTwo.id]) {
                         itemOne.qty =  itemOne.qty + itemTwo.qty;
                    }
                }
            }
            [selectArray addObject:itemOne];
        }
    }
    
    EFReturnGoods* retrunGoods = [[EFReturnGoods alloc]initWithType:type selectArray:selectArray];
    
    EFChooseReturnGoodsViewController* chooseGoods = [[EFChooseReturnGoodsViewController   alloc]initWithReturnGoosd:retrunGoods orderNo:self.orderNo];
    
    [ICNavigator pushViewController:chooseGoods animated:YES];
}

-(NSInteger)getItemTotalCount:(NSString*)id{
    int count = 0 ;
    for (NSInteger i = 0; i < self.dataArray.count; i++) {
        NSObject *object =  [self.dataArray objectAtIndex:i];
        if([object isKindOfClass:[EFReturnGoodsViewItem class]]){
            EFReturnGoodsViewItem* item = (EFReturnGoodsViewItem*)object;
            if([item.id isEqualToString:id]){
                count += item.qty;
            }
        }
    }
    return count;
}

-(void)setOkBtnText{
    
    NSMutableArray *selectArray = [NSMutableArray arrayWithCapacity:10];
    for (NSInteger i = 0; i < self.dataArray.count; i++) {
        NSObject *object =  [self.dataArray objectAtIndex:i];
        if([object isKindOfClass:[EFReturnGoodsViewItem class]]){
            EFReturnGoodsViewItem* itemOne = (EFReturnGoodsViewItem*)object;
            Boolean bCounted = false;
            for (NSInteger j = 0; j < selectArray.count; j ++) {
                EFReturnGoodsViewItem *uItem = [selectArray objectAtIndex:j];
                if ([itemOne.id isEqualToString:uItem.id]) {
                    bCounted = true;
                }
            }
            if(bCounted)
                continue;
            
            for (NSInteger j = i + 1; j < self.dataArray.count; j++){
                NSObject *object =  [self.dataArray objectAtIndex:j];
                if([object isKindOfClass:[EFReturnGoodsViewItem class]]){
                    EFReturnGoodsViewItem* itemTwo = (EFReturnGoodsViewItem*)object;
                    if ([itemOne.id isEqualToString:itemTwo.id]) {
                        itemOne.qty =  itemOne.qty + itemTwo.qty;
                    }
                }
            }
            [selectArray addObject:itemOne];
        }
    }
    if(selectArray.count == 0){
        [self.okBtn setTitle:@"下一步" forState:UIControlStateNormal];
    }else{
        [self.okBtn setTitle:@"提交退换货申请" forState:UIControlStateNormal];
    }
}

-(EFConfirmView *)confirmView{
    if(_confirmView == NULL){
        _confirmView = [[EFConfirmView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) Title:@"申请已提交" content:@"工作人员会在收到包裹后第一时间处理，请耐心等待。" block:^{
                //[self.navigationController popViewControllerAnimated:YES];
            
            EFReturnDetailViewController* returnDetail = [[EFReturnDetailViewController alloc]initWithReturnId:self.returnId];
            [ICNavigator pushViewController:returnDetail animated:YES];
            
        }];
    }
    return _confirmView;
}



@end
